<template>
  <div class="transaction-statistics">
    <div class="main-content">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>交易数据分析</span>
            <el-button-group>
              <el-button type="primary" @click="refreshData" :loading="loading">
                <el-icon><Refresh /></el-icon>刷新数据
              </el-button>
              <el-button type="success" @click="exportData">
                <el-icon><Download /></el-icon>导出数据
              </el-button>
            </el-button-group>
          </div>
        </template>

        <!-- 时间范围选择 -->
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="统计时间">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :shortcuts="dateShortcuts"
              @change="handleDateChange"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>

        <!-- 统计卡片 -->
        <el-row :gutter="20" class="data-overview">
          <el-col :span="6">
            <el-card shadow="hover">
              <template #header>
                <div class="card-header-small">
                  <span>总交易金额</span>
                  <el-tag
                    :type="
                      percentageChange.totalAmount >= 0 ? 'success' : 'danger'
                    "
                  >
                    {{ percentageChange.totalAmount >= 0 ? "+" : ""
                    }}{{ percentageChange.totalAmount }}%
                  </el-tag>
                </div>
              </template>
              <div class="card-value">
                <span class="currency">¥</span>
                <transition-group name="number">
                  <span
                    v-for="(digit, index) in formatNumber(
                      statistics.totalAmount,
                    ).split('')"
                    :key="index + digit"
                    class="digit"
                  >
                    {{ digit }}
                  </span>
                </transition-group>
              </div>
              <div class="card-compare">
                较上期
                <span
                  :class="[
                    'trend-value',
                    statistics.totalAmountGrowth >= 0
                      ? 'text-success'
                      : 'text-danger',
                  ]"
                >
                  {{ statistics.totalAmountGrowth >= 0 ? "+" : ""
                  }}{{ statistics.totalAmountGrowth }}%
                  <el-icon>
                    <component
                      :is="
                        statistics.totalAmountGrowth >= 0
                          ? 'ArrowUp'
                          : 'ArrowDown'
                      "
                    />
                  </el-icon>
                </span>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover">
              <template #header>
                <div class="card-header-small">
                  <span>总订单数</span>
                  <el-tag
                    :type="
                      percentageChange.totalOrders >= 0 ? 'success' : 'danger'
                    "
                  >
                    {{ percentageChange.totalOrders >= 0 ? "+" : ""
                    }}{{ percentageChange.totalOrders }}%
                  </el-tag>
                </div>
              </template>
              <div class="card-value">
                <transition-group name="number">
                  <span
                    v-for="(digit, index) in formatNumber(
                      statistics.totalOrders,
                    ).split('')"
                    :key="index + digit"
                    class="digit"
                  >
                    {{ digit }}
                  </span>
                </transition-group>
              </div>
              <div class="card-compare">
                较上期
                <span
                  :class="[
                    'trend-value',
                    statistics.totalOrdersGrowth >= 0
                      ? 'text-success'
                      : 'text-danger',
                  ]"
                >
                  {{ statistics.totalOrdersGrowth >= 0 ? "+" : ""
                  }}{{ statistics.totalOrdersGrowth }}%
                  <el-icon>
                    <component
                      :is="
                        statistics.totalOrdersGrowth >= 0
                          ? 'ArrowUp'
                          : 'ArrowDown'
                      "
                    />
                  </el-icon>
                </span>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover">
              <template #header>
                <div class="card-header-small">
                  <span>客单价</span>
                  <el-tag
                    :type="
                      percentageChange.averageAmount >= 0 ? 'success' : 'danger'
                    "
                  >
                    {{ percentageChange.averageAmount >= 0 ? "+" : ""
                    }}{{ percentageChange.averageAmount }}%
                  </el-tag>
                </div>
              </template>
              <div class="card-value">
                <span class="currency">¥</span>
                <transition-group name="number">
                  <span
                    v-for="(digit, index) in formatNumber(
                      statistics.averageAmount,
                    ).split('')"
                    :key="index + digit"
                    class="digit"
                  >
                    {{ digit }}
                  </span>
                </transition-group>
              </div>
              <div class="card-compare">
                较上期
                <span
                  :class="[
                    'trend-value',
                    statistics.averageAmountGrowth >= 0
                      ? 'text-success'
                      : 'text-danger',
                  ]"
                >
                  {{ statistics.averageAmountGrowth >= 0 ? "+" : ""
                  }}{{ statistics.averageAmountGrowth }}%
                  <el-icon>
                    <component
                      :is="
                        statistics.averageAmountGrowth >= 0
                          ? 'ArrowUp'
                          : 'ArrowDown'
                      "
                    />
                  </el-icon>
                </span>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover">
              <template #header>
                <div class="card-header-small">
                  <span>转化率</span>
                  <el-tag
                    :type="
                      percentageChange.conversionRate >= 0
                        ? 'success'
                        : 'danger'
                    "
                  >
                    {{ percentageChange.conversionRate >= 0 ? "+" : ""
                    }}{{ percentageChange.conversionRate }}%
                  </el-tag>
                </div>
              </template>
              <div class="card-value">
                <transition-group name="number">
                  <span
                    v-for="(digit, index) in formatNumber(
                      statistics.conversionRate,
                    ).split('')"
                    :key="index + digit"
                    class="digit"
                  >
                    {{ digit }}
                  </span>
                </transition-group>
                <span class="currency">%</span>
              </div>
              <div class="card-compare">
                较上期
                <span
                  :class="[
                    'trend-value',
                    statistics.conversionRateGrowth >= 0
                      ? 'text-success'
                      : 'text-danger',
                  ]"
                >
                  {{ statistics.conversionRateGrowth >= 0 ? "+" : ""
                  }}{{ statistics.conversionRateGrowth }}%
                  <el-icon>
                    <component
                      :is="
                        statistics.conversionRateGrowth >= 0
                          ? 'ArrowUp'
                          : 'ArrowDown'
                      "
                    />
                  </el-icon>
                </span>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 图表区域 -->
        <div class="charts-container">
          <el-row :gutter="20">
            <el-col :span="16">
              <el-card class="chart-card">
                <template #header>
                  <div class="chart-header">
                    <span>交易趋势</span>
                    <el-radio-group v-model="trendType" size="small">
                      <el-radio-button label="amount">金额</el-radio-button>
                      <el-radio-button label="orders">订单数</el-radio-button>
                    </el-radio-group>
                  </div>
                </template>
                <div ref="trendChart" class="chart"></div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card class="chart-card">
                <template #header>
                  <div class="chart-header">
                    <span>支付方式分布</span>
                  </div>
                </template>
                <div ref="paymentChart" class="chart"></div>
              </el-card>
            </el-col>
          </el-row>
          <el-row :gutter="20" class="mt-4">
            <el-col :span="12">
              <el-card class="chart-card">
                <template #header>
                  <div class="chart-header">
                    <span>商品类型分布</span>
                  </div>
                </template>
                <div ref="productChart" class="chart"></div>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card class="chart-card">
                <template #header>
                  <div class="chart-header">
                    <span>时段分布</span>
                  </div>
                </template>
                <div ref="timeChart" class="chart"></div>
              </el-card>
            </el-col>
          </el-row>
        </div>

        <!-- 交易明细 -->
        <el-card class="mt-4">
          <template #header>
            <div class="detail-header">
              <span>交易明细</span>
            </div>
          </template>
          <el-table
            v-loading="loading"
            :data="transactionList"
            style="width: 100%"
            border
            stripe
            highlight-current-row
          >
            <el-table-column prop="orderNo" label="订单编号" width="180" />
            <el-table-column
              prop="productName"
              label="商品名称"
              min-width="200"
              show-overflow-tooltip
            />
            <el-table-column prop="productType" label="商品类型" width="100">
              <template #default="{ row }">
                <el-tag>{{ getProductTypeLabel(row.productType) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="交易金额" width="120">
              <template #default="{ row }">
                <span class="amount">¥{{ row.amount.toFixed(2) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="paymentMethod" label="支付方式" width="100">
              <template #default="{ row }">
                <el-tag type="info">{{
                  getPaymentMethodLabel(row.paymentMethod)
                }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="交易状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.status)">
                  {{ getStatusLabel(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="160" />
          </el-table>

          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick } from "vue";
import { ElMessage } from "element-plus";
import * as echarts from "echarts";
import { debounce } from "lodash-es";
import { Refresh, Download, ArrowUp, ArrowDown } from "@element-plus/icons-vue";

// 搜索表单
const searchForm = reactive({
  dateRange: [],
});

// 日期快捷选项
const dateShortcuts = [
  {
    text: "最近一周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: "最近一月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
  {
    text: "最近三月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    },
  },
];

// 统计数据
const statistics = reactive({
  totalAmount: 1286560,
  totalAmountGrowth: 15.4,
  totalOrders: 12860,
  totalOrdersGrowth: 8.2,
  averageAmount: 1000.43,
  averageAmountGrowth: 6.7,
  conversionRate: 35.8,
  conversionRateGrowth: 2.5,
});

// 环比变化
const percentageChange = reactive({
  totalAmount: 15.4,
  totalOrders: 8.2,
  averageAmount: 6.7,
  conversionRate: 2.5,
});

// 图表相关
const trendType = ref("amount");
const trendChart = ref(null);
const paymentChart = ref(null);
const productChart = ref(null);
const timeChart = ref(null);
let charts = [];

// 加载状态
const loading = ref(false);

// 表格数据
const transactionList = ref([
  {
    orderNo: "DD20240301001",
    productName: "象鼻山门票",
    productType: "ticket",
    amount: 128.0,
    paymentMethod: "wechat",
    status: "success",
    createTime: "2024-03-01 10:00:00",
  },
  {
    orderNo: "DD20240301002",
    productName: "桂林大酒店豪华套房",
    productType: "hotel",
    amount: 888.0,
    paymentMethod: "alipay",
    status: "success",
    createTime: "2024-03-01 10:15:00",
  },
  {
    orderNo: "DD20240301003",
    productName: "漓江游船+午餐套餐",
    productType: "package",
    amount: 366.0,
    paymentMethod: "unionpay",
    status: "pending",
    createTime: "2024-03-01 10:30:00",
  },
]);

// 分页
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(28);

// 获取商品类型标签
const getProductTypeLabel = (type) => {
  const types = {
    ticket: "门票",
    hotel: "酒店",
    package: "套餐",
  };
  return types[type] || type;
};

// 获取支付方式标签
const getPaymentMethodLabel = (method) => {
  const methods = {
    wechat: "微信支付",
    alipay: "支付宝",
    unionpay: "银联",
  };
  return methods[method] || method;
};

// 获取状态标签
const getStatusLabel = (status) => {
  const statuses = {
    success: "成功",
    pending: "处理中",
    failed: "失败",
  };
  return statuses[status] || status;
};

// 获取状态样式
const getStatusType = (status) => {
  const types = {
    success: "success",
    pending: "warning",
    failed: "danger",
  };
  return types[status] || "";
};

// 格式化数字
const formatNumber = (num) => {
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};

// 加载数据
const loadData = () => {
  loading.value = true;
  try {
    // 模拟API调用延迟
    setTimeout(() => {
      // 更新统计数据
      Object.assign(statistics, {
        totalAmount: 1286560,
        totalAmountGrowth: 15.4,
        totalOrders: 12860,
        totalOrdersGrowth: 8.2,
        averageAmount: 1000.43,
        averageAmountGrowth: 6.7,
        conversionRate: 35.8,
        conversionRateGrowth: 2.5,
      });

      // 更新环比数据
      Object.assign(percentageChange, {
        totalAmount: 15.4,
        totalOrders: 8.2,
        averageAmount: 6.7,
        conversionRate: 2.5,
      });

      // 更新表格数据
      transactionList.value = [
        {
          orderNo: "DD20240301001",
          productName: "象鼻山门票",
          productType: "ticket",
          amount: 128.0,
          paymentMethod: "wechat",
          status: "success",
          createTime: "2024-03-01 10:00:00",
        },
        {
          orderNo: "DD20240301002",
          productName: "桂林大酒店豪华套房",
          productType: "hotel",
          amount: 888.0,
          paymentMethod: "alipay",
          status: "success",
          createTime: "2024-03-01 10:15:00",
        },
        {
          orderNo: "DD20240301003",
          productName: "漓江游船+午餐套餐",
          productType: "package",
          amount: 366.0,
          paymentMethod: "unionpay",
          status: "pending",
          createTime: "2024-03-01 10:30:00",
        },
        {
          orderNo: "DD20240301004",
          productName: "阳朔西街导游服务",
          productType: "guide",
          amount: 200.0,
          paymentMethod: "wechat",
          status: "success",
          createTime: "2024-03-01 10:45:00",
        },
        {
          orderNo: "DD20240301005",
          productName: "龙脊梯田一日游",
          productType: "package",
          amount: 468.0,
          paymentMethod: "alipay",
          status: "success",
          createTime: "2024-03-01 11:00:00",
        },
        {
          orderNo: "DD20240301006",
          productName: "兴坪古镇特色客栈",
          productType: "hotel",
          amount: 299.0,
          paymentMethod: "wechat",
          status: "failed",
          createTime: "2024-03-01 11:15:00",
        },
        {
          orderNo: "DD20240301007",
          productName: "银子岩门票",
          productType: "ticket",
          amount: 98.0,
          paymentMethod: "alipay",
          status: "success",
          createTime: "2024-03-01 11:30:00",
        },
        {
          orderNo: "DD20240301008",
          productName: "城徽酒店豪华套房",
          productType: "hotel",
          amount: 1288.0,
          paymentMethod: "unionpay",
          status: "success",
          createTime: "2024-03-01 11:45:00",
        },
        {
          orderNo: "DD20240301009",
          productName: "訾洲夜游船票",
          productType: "ticket",
          amount: 150.0,
          paymentMethod: "wechat",
          status: "pending",
          createTime: "2024-03-01 12:00:00",
        },
        {
          orderNo: "DD20240301010",
          productName: "桂林千古情演出票",
          productType: "ticket",
          amount: 268.0,
          paymentMethod: "alipay",
          status: "success",
          createTime: "2024-03-01 12:15:00",
        },
      ];

      // 更新图表数据
      const chartData = {
        trend: {
          dates: ["3-1", "3-2", "3-3", "3-4", "3-5", "3-6", "3-7"],
          amounts: [156000, 142000, 168000, 145000, 178000, 165000, 189000],
          orders: [1560, 1420, 1680, 1450, 1780, 1650, 1890],
        },
        payment: [
          { value: 48560, name: "微信支付", percentage: 45 },
          { value: 35680, name: "支付宝", percentage: 33 },
          { value: 15600, name: "银联", percentage: 14 },
          { value: 8600, name: "其他", percentage: 8 },
        ],
        product: [
          { name: "门票", value: 386000 },
          { name: "酒店", value: 425000 },
          { name: "餐饮", value: 186000 },
          { name: "购物", value: 156000 },
          { name: "其他", value: 98000 },
        ],
        time: {
          hours: [
            "00:00",
            "03:00",
            "06:00",
            "09:00",
            "12:00",
            "15:00",
            "18:00",
            "21:00",
          ],
          amounts: [
            35000, 12000, 25000, 156000, 186000, 168000, 198000, 142000,
          ],
          orders: [350, 120, 250, 1560, 1860, 1680, 1980, 1420],
        },
      };

      // 更新图表
      updateCharts(chartData);

      loading.value = false;
      ElMessage.success("数据加载成功");
    }, 1000);
  } catch (error) {
    console.error("Failed to load data:", error);
    loading.value = false;
    ElMessage.error("数据加载失败");
  }
};

// 更新图表数据
const updateCharts = (data) => {
  charts.forEach((chart) => {
    if (chart) {
      try {
        chart.dispose();
      } catch (error) {
        console.error("Failed to dispose chart:", error);
      }
    }
  });
  charts = [];

  nextTick(() => {
    // 交易趋势图
    if (trendChart.value) {
      const trend = echarts.init(trendChart.value);
      const trendOption = {
        tooltip: {
          trigger: "axis",
          formatter: (params) => {
            let result = params[0].axisValue + "<br/>";
            params.forEach((param) => {
              const value =
                param.seriesName === "交易金额"
                  ? "¥" + formatNumber(param.value)
                  : formatNumber(param.value);
              result +=
                param.marker + param.seriesName + ": " + value + "<br/>";
            });
            return result;
          },
        },
        legend: {
          data: ["交易金额", "订单数量"],
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: data.trend.dates,
        },
        yAxis: [
          {
            type: "value",
            name: "金额",
            axisLabel: {
              formatter: "¥{value}",
            },
          },
          {
            type: "value",
            name: "订单数",
            axisLabel: {
              formatter: "{value}",
            },
          },
        ],
        series: [
          {
            name: "交易金额",
            type: "line",
            smooth: true,
            data: data.trend.amounts,
            itemStyle: {
              color: "#409EFF",
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "rgba(64, 158, 255, 0.3)" },
                { offset: 1, color: "rgba(64, 158, 255, 0.1)" },
              ]),
            },
          },
          {
            name: "订单数量",
            type: "line",
            yAxisIndex: 1,
            smooth: true,
            data: data.trend.orders,
            itemStyle: {
              color: "#67C23A",
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "rgba(103, 194, 58, 0.3)" },
                { offset: 1, color: "rgba(103, 194, 58, 0.1)" },
              ]),
            },
          },
        ],
      };
      trend.setOption(trendOption);
      charts.push(trend);
    }

    // 支付方式分布图
    if (paymentChart.value) {
      const payment = echarts.init(paymentChart.value);
      const paymentOption = {
        tooltip: {
          trigger: "item",
          formatter: "{b}: ¥{c} ({d}%)",
        },
        legend: {
          orient: "vertical",
          right: "5%",
          top: "center",
        },
        series: [
          {
            name: "支付方式",
            type: "pie",
            radius: ["40%", "70%"],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderWidth: 2,
            },
            label: {
              show: false,
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 20,
                fontWeight: "bold",
              },
            },
            data: [
              {
                value: data.payment[0].value,
                name: "微信支付",
                itemStyle: { color: "#67C23A" },
              },
              {
                value: data.payment[1].value,
                name: "支付宝",
                itemStyle: { color: "#409EFF" },
              },
              {
                value: data.payment[2].value,
                name: "银联",
                itemStyle: { color: "#E6A23C" },
              },
              {
                value: data.payment[3].value,
                name: "其他",
                itemStyle: { color: "#909399" },
              },
            ],
          },
        ],
      };
      payment.setOption(paymentOption);
      charts.push(payment);
    }

    // 商品类型分布图
    if (productChart.value) {
      const product = echarts.init(productChart.value);
      const productOption = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
          formatter: "{b}: ¥{c}",
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: data.product.map((item) => item.name),
        },
        yAxis: {
          type: "value",
          axisLabel: {
            formatter: "¥{value}",
          },
        },
        series: [
          {
            name: "交易金额",
            type: "bar",
            data: data.product.map((item, index) => ({
              value: item.value,
              itemStyle: {
                color: ["#409EFF", "#67C23A", "#E6A23C", "#F56C6C", "#909399"][
                  index
                ],
              },
            })),
            barWidth: "40%",
            itemStyle: {
              borderRadius: [4, 4, 0, 0],
            },
            label: {
              show: true,
              position: "top",
              formatter: "¥{c}",
            },
          },
        ],
      };
      product.setOption(productOption);
      charts.push(product);
    }

    // 时段分布图
    if (timeChart.value) {
      const time = echarts.init(timeChart.value);
      const timeOption = {
        tooltip: {
          trigger: "axis",
          formatter: (params) => {
            let result = params[0].axisValue + "<br/>";
            params.forEach((param) => {
              const value =
                param.seriesName === "交易金额"
                  ? "¥" + formatNumber(param.value)
                  : formatNumber(param.value);
              result +=
                param.marker + param.seriesName + ": " + value + "<br/>";
            });
            return result;
          },
        },
        legend: {
          data: ["交易金额", "订单数量"],
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: data.time.hours,
        },
        yAxis: [
          {
            type: "value",
            name: "金额",
            axisLabel: {
              formatter: "¥{value}",
            },
          },
          {
            type: "value",
            name: "订单数",
            axisLabel: {
              formatter: "{value}",
            },
          },
        ],
        series: [
          {
            name: "交易金额",
            type: "line",
            smooth: true,
            data: data.time.amounts,
            itemStyle: {
              color: "#409EFF",
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "rgba(64, 158, 255, 0.3)" },
                { offset: 1, color: "rgba(64, 158, 255, 0.1)" },
              ]),
            },
          },
          {
            name: "订单数量",
            type: "line",
            yAxisIndex: 1,
            smooth: true,
            data: data.time.orders,
            itemStyle: {
              color: "#67C23A",
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "rgba(103, 194, 58, 0.3)" },
                { offset: 1, color: "rgba(103, 194, 58, 0.1)" },
              ]),
            },
          },
        ],
      };
      time.setOption(timeOption);
      charts.push(time);
    }
  });
};

// 刷新数据
const refreshData = () => {
  handleSearch();
};

// 导出数据
const exportData = () => {
  // 实现导出逻辑
};

// 日期变化处理
const handleDateChange = () => {
  handleSearch();
};

// 搜索
const handleSearch = () => {
  // 实现搜索逻辑
};

// 重置搜索
const resetSearch = () => {
  searchForm.dateRange = [];
  handleSearch();
};

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  handleSearch();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  handleSearch();
};

// 防抖处理的重绘函数
const debouncedResize = debounce(() => {
  charts.forEach((chart) => {
    if (chart) {
      try {
        chart.resize();
      } catch (error) {
        console.error("Failed to resize chart:", error);
      }
    }
  });
}, 100);

// 监听主题变化
const handleThemeChange = debounce(() => {
  const isDarkMode =
    document.documentElement.getAttribute("data-theme") === "dark";
  charts.forEach((chart) => {
    if (chart) {
      try {
        chart.dispose();
      } catch (error) {
        console.error("Failed to dispose chart:", error);
      }
    }
  });
  charts = [];
  nextTick(() => {
    updateCharts({
      trend: {
        dates: ["3-1", "3-2", "3-3", "3-4", "3-5", "3-6", "3-7"],
        amounts: [156000, 142000, 168000, 145000, 178000, 165000, 189000],
        orders: [1560, 1420, 1680, 1450, 1780, 1650, 1890],
      },
      payment: [
        { value: 48560, name: "微信支付", percentage: 45 },
        { value: 35680, name: "支付宝", percentage: 33 },
        { value: 15600, name: "银联", percentage: 14 },
        { value: 8600, name: "其他", percentage: 8 },
      ],
      product: [
        { name: "门票", value: 386000 },
        { name: "酒店", value: 425000 },
        { name: "餐饮", value: 186000 },
        { name: "购物", value: 156000 },
        { name: "其他", value: 98000 },
      ],
      time: {
        hours: [
          "00:00",
          "03:00",
          "06:00",
          "09:00",
          "12:00",
          "15:00",
          "18:00",
          "21:00",
        ],
        amounts: [35000, 12000, 25000, 156000, 186000, 168000, 198000, 142000],
        orders: [350, 120, 250, 1560, 1860, 1680, 1980, 1420],
      },
    });
  });
}, 100);

// 页面加载时获取数据
onMounted(() => {
  loadData();
  window.addEventListener("resize", debouncedResize);
  window.addEventListener("theme-change", handleThemeChange);
});

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener("resize", debouncedResize);
  window.removeEventListener("theme-change", handleThemeChange);

  // 清理防抖函数
  debouncedResize.cancel();
  handleThemeChange.cancel();

  charts.forEach((chart) => {
    if (chart) {
      try {
        chart.dispose();
      } catch (error) {
        console.error("Failed to dispose chart:", error);
      }
    }
  });
});
</script>

<style lang="scss" scoped>
.transaction-statistics {
  padding: 20px;
}

.main-content {
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background: var(--el-fill-color-light);
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 var(--el-box-shadow-light);
}

.data-overview {
  margin-bottom: 20px;

  :deep(.el-card) {
    transition: all 0.3s ease;
    border: none;
    background: var(--el-bg-color-overlay);

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }

    .el-card__header {
      border-bottom: 1px solid var(--el-border-color-light);
      padding: 15px 20px;
    }
  }
}

.card-header-small {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;

  .el-tag {
    padding: 4px 8px;
    border-radius: 4px;
    font-weight: bold;
  }
}

.card-value {
  font-size: 28px;
  font-weight: bold;
  margin: 15px 0;
  color: var(--el-text-color-primary);
  transition: color 0.3s ease;
  display: flex;
  align-items: baseline;
  gap: 4px;

  .currency {
    font-size: 16px;
    color: var(--el-text-color-secondary);
  }

  .digit {
    display: inline-block;
    transition: all 0.3s ease;
  }
}

.card-compare {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  display: flex;
  align-items: center;
  gap: 8px;

  .trend-value {
    display: flex;
    align-items: center;
    gap: 4px;

    &.text-success {
      color: var(--el-color-success);
    }

    &.text-danger {
      color: var(--el-color-danger);
    }

    .el-icon {
      font-size: 12px;
    }
  }
}

.charts-container {
  margin-top: 20px;

  .chart-card {
    margin-bottom: 20px;
    transition: all 0.3s ease;
    background: var(--el-bg-color-overlay);
    border: none;

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }
  }

  .chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    border-bottom: 1px solid var(--el-border-color-light);

    span {
      font-size: 16px;
      font-weight: bold;
      color: var(--el-text-color-primary);
    }
  }

  .chart {
    height: 300px;
    padding: 20px;
  }
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.dark) {
  .transaction-statistics {
    background-color: var(--el-bg-color);
  }

  .search-form {
    background: var(--el-bg-color-overlay);
    border: 1px solid var(--el-border-color-darker);
  }

  .el-card {
    background-color: var(--el-bg-color-overlay);
    border: 1px solid var(--el-border-color-darker);

    &:hover {
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
    }
  }

  .chart-card {
    background-color: var(--el-bg-color-overlay);
    border: 1px solid var(--el-border-color-darker);
  }

  .card-value {
    color: var(--el-text-color-primary);
  }

  .card-compare {
    color: var(--el-text-color-secondary);
  }
}

.number-enter-active,
.number-leave-active {
  transition: all 0.3s ease;
}

.number-enter-from {
  opacity: 0;
  transform: translateY(20px);
}

.number-leave-to {
  opacity: 0;
  transform: translateY(-20px);
}
</style>
